package handler

import (
	"adm-mysql/internal/db"
	"adm-mysql/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

//	CreateDBInstance godoc
//	@Summary		CreateDBInstance
//	@Description	添加实例信息
//	@Tags			DBInstance
//	@Param			param	body	db.CreateDBInstanceParams	true	"添加数据库实例信息"
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	db.DbInstance
//	@Router			/database/instance/ [post]
//
// CreateDBInstance 添加实例信息
func CreateDBInstance(c *gin.Context) {
	var param db.CreateDBInstanceParams
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, err)
		return
	}
	hsPassword, err := utils.EncryptAES(param.Password)
	if err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	param.Password = hsPassword
	result, err := db.NewStore().CreateDBInstance(c.Request.Context(), param)
	if err != nil {
		c.JSON(http.StatusInternalServerError, err)
		return
	}
	c.JSON(http.StatusOK, result)
}

//	DeleteDBInstance godoc
//	@Summary		DeleteDBInstance
//	@Description	删除数据库实例信息
//	@Tags			DBInstance
//	@Param			id	path	string	true	"id"
//	@Accept			json
//	@Produce		json
//	@Success		200	{string}	string	"删除成功"
//	@Router			/database/instance/{id}/ [delete]
//
// DeleteDBInstance 删除数据库实例信息
func DeleteDBInstance(c *gin.Context) {
	param := c.Param("id")
	id, err := strconv.Atoi(param)
	if err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	err = db.NewStore().DeleteDBInstance(c.Request.Context(), int64(id))
	if err != nil {
		c.JSON(http.StatusInternalServerError, err)
		return
	}
	c.JSON(http.StatusOK, "删除成功")
}

//	UpdateDBInstance godoc
//	@Summary		UpdateDBInstance
//	@Description	修改数据库实例信息
//	@Tags			DBInstance
//	@Param			param	body	db.UpdateDBInstanceParams	true	"更新参数"
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	db.DbInstance
//	@Router			/database/instance/ [put]
//
// UpdateDBInstance 修改数据库实例信息
func UpdateDBInstance(c *gin.Context) {
	var param db.UpdateDBInstanceParams
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	hsPassword, err := utils.EncryptAES(param.Password)
	if err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	param.Password = hsPassword
	result, err := db.NewStore().UpdateDBInstance(c.Request.Context(), param)
	if err != nil {
		c.JSON(http.StatusInternalServerError, err)
		return
	}
	c.JSON(http.StatusOK, result)
}

// ListDBInstances godoc
//
//	@Summary		ListDBInstance
//	@Description	获取数据库实例信息
//	@Tags			DBInstance
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	[]db.DbInstance
//	@Router			/database/instances/ [get]
//
// ListDBInstances 获取数据库实例信息
func ListDBInstances(c *gin.Context) {
	result, err := db.NewStore().ListDBInstance(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, err.Error())
		return
	}
	c.JSON(http.StatusOK, result)
}
